const db_JQL = uniCloud.databaseForJQL();
const { getQuarter, getQuarterStartEndTimestamp } = require('../../common/time');
module.exports = async function(options = {}) {
	const { characterId } = options;
	const token = this.getUniIdToken();
	const timeResult = getQuarterStartEndTimestamp(getQuarter().year, getQuarter().quarter);
	if (!token) {
		throw new Error('非法访问');
	}
	if (!characterId) {
		throw new Error('缺少参数');
	}
	const collection = db_JQL.collection('a-dz-complete-stats-list');
	const where = { characterId, createTime: db_JQL.command.gt(timeResult.start).and(db_JQL.command.lt(timeResult.end)) };
	const [res] = await Promise.all([
		collection
		.where(where)
		.field('characterId,keystrokeStats')
		.get()
	])

	function mergeKeystrokeStats(statsArray) {
		const mergedStats = {};
		statsArray.forEach(stats => {
			const keystrokeStats = stats.keystrokeStats;
			for (const key in keystrokeStats) {
				if (mergedStats.hasOwnProperty(key)) {
					mergedStats[key].success += keystrokeStats[key].success;
					mergedStats[key].error += keystrokeStats[key].error;
				} else {
					mergedStats[key] = { success: keystrokeStats[key].success, error: keystrokeStats[key].error };
				}
			}
		});
		return mergedStats;
	}
	const result = {
		characterId,
		mergedStats: mergeKeystrokeStats(res.data)
	}
	return {
		code: 0,
		data: result,
		msg: '获取成功'
	}
}